package com.ivr.cm.http;

import java.io.IOException;
import java.io.OutputStream;
import java.util.AbstractMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.ivr.cm.cache.Cacheable;
import com.ivr.cm.util.SpringServiceUtil;

public class CacheController implements Controller {
	private static Logger logger = Logger.getLogger(CacheController.class);

	@SuppressWarnings("unchecked")
	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		OutputStream os = response.getOutputStream();
		String bean = request.getParameter("bean");
		
		Object cache = null;
		try{
			Cacheable service = (Cacheable) SpringServiceUtil.getService(bean);
			cache = service.getCache();
		}catch (Exception e) {
			logger.info(String.format("[%s]获得缓存类异常%s", bean,ExceptionUtils.getFullStackTrace(e)));
			output(os, String.format("[%s]获得缓存类异常%s", bean,ExceptionUtils.getFullStackTrace(e)));
		}
		//根据cache的类型来打印输出
		if(cache instanceof AbstractMap){
			AbstractMap cacheMap = (AbstractMap)cache;
			Set<Map.Entry<Object, Object>> set = cacheMap.entrySet();
			Iterator<Map.Entry<Object, Object>> iterator = set.iterator();
			
			while(iterator.hasNext()){
				Map.Entry<Object, Object> entry = iterator.next();
				os.write(entry.getKey().toString().getBytes());
				os.write("\t".getBytes());
				
				if(entry.getValue() instanceof List){
					for(Object obj : (List)entry.getValue()){
						os.write(new String(obj.toString().getBytes("gbk")).getBytes());
						os.write("\n".getBytes());
					}
				}else{
					os.write(entry.getValue().toString().getBytes());
					os.write("\n".getBytes());
				}
				
			}
			
		}else{
			output(os, cache.toString());
		}
		return null;
	}
	
	private void output(OutputStream out,String message) throws IOException{
		out.write(message.getBytes());
		out.flush();
		out.close();
	}
}